<template>
  <div id="ship">
    <h1>发货详情</h1>
    <el-form label-width="130px" class="commonFrom">
      <el-form-item label="订单编号：" style="margin-bottom: 3px !important"> {{ orderFrom.orderNo }}</el-form-item>
      <el-form-item label="关联合同：" style="margin-bottom: 3px !important">
        {{ orderFrom.contractNo }}-{{ orderFrom.proName }}
      </el-form-item>
      <el-form-item label="物流方式：" style="margin-bottom: 3px">
        <el-radio-group v-model="shipFrom.deliveryType">
          <el-radio :label="1">自发物流</el-radio>
          <el-radio :label="2">其他物流</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="约定交货日期" style="margin-bottom: 12px !important">
        <el-date-picker
          size="small"
          style="width: 280px"
          v-model.trim="orderFrom.agreedDeliveryDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择日期"
          disabled
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="交付地点：" style="width: 100% !important">
        <el-select style="width: 150px" size="small" v-model.trim="orderFrom.province" placeholder="请选择省" disabled>
        </el-select>
        <el-select
          style="width: 150px; margin-left: 10px"
          size="small"
          v-model.trim="orderFrom.city"
          placeholder="请选择市"
          disabled
        >
        </el-select>
        <el-select
          style="width: 150px; margin-left: 10px"
          size="small"
          v-model.trim="orderFrom.area"
          placeholder="请选择区"
          disabled
        >
        </el-select>
        <el-input
          style="width: 280px; margin-left: 10px"
          size="small"
          disabled
          placeholder="请填写详细地址"
          v-model.trim="orderFrom.detailAddress"
        >
        </el-input>
      </el-form-item>
    </el-form>
    <div style="margin: 9px 0 20px">
      以下甲方即指合同中采购方，乙方即指合同中的供应方:乙方根据甲方实际需要，以{{ orderFrom.takeEffectDate }}签订的 《
      {{ orderFrom.contractNo }}-{{ orderFrom.proName }}》 为依据，乙方将按下表所列材料(设备)名
      称、品牌、型号.规格、数量.交货日期送至甲方指定的交货地点送货。
    </div>
    <h1>货品清单</h1>
    <div class="btn_box">
      <div>
        <el-button size="small" icon="iconfont icon-add" class="commonBtn1" @click="addMaterial('合同内')"
          >添加合同内材料</el-button
        >
        <el-button size="small" icon="iconfont icon-add" class="commonBtn1" @click="addMaterial('合同外')"
          >添加合同外材料</el-button
        >
        <el-button size="small" class="commonBtn" @click="remove">清空</el-button>
      </div>
      <p>
        总合计：<span style="font-size: 24px; color: #333">{{ shipFrom.realAmountPrice || '0' }}</span
        >元
      </p>
    </div>
    <div style="margin-bottom: 20px">
      <el-table
        :data="shipFrom.orderDeliveryDetailsList"
        border
        class="bidding"
        ref="jdjgTable"
        :header-cell-style="{ padding: '0px', background: '#F2F3F7' }"
        :row-class-name="tabRowClassName"
      >
        <el-table-column width="60" align="center" type="index" label="序号">
          <template slot-scope="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column label="材料类型" align="center" prop="productTypes" width="120">
          <template slot-scope="scope">
            <div>
              {{ scope.row.productTypes == 1 ? '合同内' : '合同外' }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="材料名称" align="center" prop="materialName" width="160"> </el-table-column>
        <el-table-column label="规格型号" align="center" prop="model" width="160">
          <template slot-scope="scope">
            <el-select
              size="small"
              v-if="scope.row.productTypes == 2"
              v-model.trim="scope.row.model"
              placeholder="请选择"
              @change="categoryChange"
              @visible-change="selectFocus($event, scope.row.materialId)"
            >
              <el-option
                v-for="item in scope.row.modelSelectList"
                :label="item.specsName"
                :value="item.specsName"
                :key="item.id"
              ></el-option>
            </el-select>
            <div v-else>
              {{ scope.row.model }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="单位" align="center" prop="company" width="120"> </el-table-column>
        <el-table-column label="参数指标" align="center" prop="parameterIndex" width="160" show-overflow-tooltip>
          <template slot-scope="scope">
            <div v-if="scope.row.productTypes == 1" class="text_hidde">
              {{ scope.row.parameterIndex }}
            </div>
            <div v-else>
              <tool-tip-input
                :size="'small'"
                :deviationContent="scope.row.parameterIndex"
                v-model.trim="scope.row.parameterIndex"
                :placeholder="'请输入参数指标'"
              ></tool-tip-input>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="单价" align="center" prop="unitPrice" width="140">
          <template slot-scope="scope">
            <div>
              <el-input
                v-model.trim="scope.row.unitPrice"
                placeholder="请输入单价"
                size="small"
                @input="contractPrice($event, scope.$index, 'unitPrice')"
              ></el-input>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="数量" align="center" prop="purchaseQuantity" width="140">
          <template slot-scope="scope">
            <div>
              <el-input
                v-model.trim="scope.row.purchaseQuantity"
                placeholder="请输入数量"
                size="small"
                @input="contractPrice($event, scope.$index, 'purchaseQuantity')"
              ></el-input>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="总价" align="center" prop="totalPrice" width="160"> </el-table-column>
        <el-table-column label="操作" align="center" width="140" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" class="ty czBtn" @click="delTableItem(scope.$index)"> 删除 </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <h1>物流信息</h1>
    <el-form label-width="130px" class="commonFrom">
      <el-form-item label="物流方式：" style="margin-bottom: 3px">
        {{ shipFrom.deliveryType == 1 ? '自发物流' : '其他物流' }}
      </el-form-item>
      <el-form-item label="车牌号：" style="margin-bottom: 3px" v-if="shipFrom.deliveryType == 1">
        <el-input
          style="width: 280px"
          size="small"
          placeholder="请输入车牌号，多个使用逗号隔开"
          v-model.trim="shipFrom.licenseNumber"
        >
        </el-input>
      </el-form-item>
      <el-form-item label="物流单号：" style="margin-bottom: 3px" v-else>
        <el-input
          style="width: 280px"
          size="small"
          placeholder="请输入物流单号，多个使用逗号隔开"
          v-model.trim="shipFrom.trackingNumber"
        >
        </el-input>
      </el-form-item>
      <el-form-item label="发货日期：" style="margin-bottom: 12px !important; margin-right: 400px">
        <el-date-picker
          size="small"
          style="width: 280px"
          :picker-options="pickerOptions0"
          v-model.trim="shipFrom.deliveryDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择日期"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="承运人：" style="margin-bottom: 3px">
        <el-input style="width: 280px" size="small" placeholder="请输入承运人姓名" v-model.trim="shipFrom.carrier">
        </el-input>
      </el-form-item>
      <el-form-item label="承运人联系电话：" style="margin-bottom: 3px">
        <el-input
          style="width: 280px"
          size="small"
          placeholder="请输入承运人联系电话"
          v-model.trim="shipFrom.carrierPhone"
        >
        </el-input>
      </el-form-item>
    </el-form>
    <h1>联系方式</h1>
    <el-form label-width="130px" class="commonFrom">
      <el-form-item label="供应方联系人：" style="margin-bottom: 3px !important">
        <el-input style="width: 280px" size="small" placeholder="请输入供应方联系人" v-model.trim="shipFrom.supplier">
        </el-input>
      </el-form-item>
      <el-form-item label="供应方联系电话：" style="margin-bottom: 3px !important">
        <el-input
          style="width: 280px"
          size="small"
          placeholder="请输入供应方联系电话"
          v-model.trim="shipFrom.supplierPhone"
        >
        </el-input>
      </el-form-item>
      <el-form-item label="验收联系人：" style="margin-bottom: 3px"> {{ shipFrom.acceptance || '--' }} </el-form-item>
      <el-form-item label="验收联系电话：" style="margin-bottom: 3px">
        {{ shipFrom.acceptancePhone || '--' }}
      </el-form-item>
    </el-form>
    <h1>发货附件上传</h1>
    <el-button size="small" class="commonBtn1" style="margin: 20px 0 0" @click="uploadClick">上传附件</el-button>
    <div class="upload-wrap">
      <el-upload
        class="upload-demo"
        :headers="loadHeader"
        multiple
        accept=".jpg,.png,.pdf"
        :action="urlUpload"
        :on-remove="fileRemove"
        :on-success="uploadSuccess"
        :before-upload="beforeUpload"
        :on-exceed="onExceed"
        :file-list="fileList"
      >
        <template slot="trigger">
          <div ref="biddUpload"></div>
        </template>
      </el-upload>
    </div>
    <h1>验收说明</h1>
    <el-input
      type="textarea"
      :autosize="{ minRows: 3 }"
      placeholder="请输入验收说明"
      v-model.trim="shipFrom.acceptanceDescription"
      style="margin: 20px 0"
    >
    </el-input>
    <div class="footer">
      <el-button size="small" class="commonBtn" @click="closeBtn">取消</el-button>
      <el-button size="small" class="commonBtn1" @click="subBtn">确定</el-button>
    </div>

    <el-dialog
      width="1200px"
      :center="true"
      title="选择材料"
      append-to-body
      :close-on-click-modal="false"
      :visible.sync="addMaterialVisiable"
      v-if="addMaterialVisiable"
    >
      <add-contract-material :contractId="contractId" @close="materialClose"></add-contract-material>
    </el-dialog>
    <el-dialog
      class="dialog_detail"
      :center="true"
      append-to-body
      :close-on-click-modal="false"
      width="1200px"
      title="选择新品类"
      :visible.sync="materialVisible"
      v-if="materialVisible"
    >
      <tertiary-material :list="[]" @close="newMaterialClose"> </tertiary-material>
    </el-dialog>
  </div>
</template>

<script>
import ToolTipInput from '../../../../components/ToolTipInput.vue'
import tertiaryMaterial from '../../../../components/TertiaryMaterial'
import AddContractMaterial from './AddContractMaterial.vue'
export default {
  props: {
    orderId: {
      type: [String, Number],
      require: true
    },
    contractId: {
      type: [String, Number],
      require: true
    }
  },
  data() {
    return {
      pickerOptions0: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7
        }
      },
      num: 0,
      fileSuccess: true,
      urlUpload: this.GLOBAL.weburl + '/api/file/upload',
      fileList: [],
      materialVisible: false,
      addMaterialVisiable: false,
      orderFrom: {},
      shipFrom: {
        acceptance: '',
        acceptanceDescription: '',
        acceptancePhone: '',
        carrier: '',
        carrierPhone: '',
        contractOrderId: 0,
        deliveryDate: '',
        deliveryType: 1,
        licenseNumber: '',
        orderDeliveryDetailsList: [],
        realAmountPrice: '',
        supplier: '',
        attachUrl: '',
        supplierPhone: '',
        trackingNumber: ''
      }
    }
  },
  computed: {
    loadHeader() {
      let token = this.common.getCookie('materialsToken')
      const header = {}
      header[this.GLOBAL.tokenName] = token
      return header
    }
  },
  components: { AddContractMaterial, tertiaryMaterial, ToolTipInput },
  mounted() {
    this.getOrderData()
  },
  methods: {
    // 触发上传
    uploadClick() {
      this.$refs.biddUpload.click()
    },
    // 删除文件
    fileRemove(file, files) {
      this.fileList = files
      this.num = this.fileList.length
    },
    // 文件上传前进行文件大小检测
    beforeUpload(file) {
      this.fileSuccess = false
      const isLt = file.size / 1024 / 1024 / 10 <= 1
      if (!isLt) {
        this.$message.error('单个文件大小不能超过10M,请检查文件大小并重新尝试')
      }
      return isLt
    },
    // 文件上传前判断是否超过同时上传文件个数限制
    onExceed() {
      this.$message.error('最多支持同时上传3个文件，请重新上传')
    },
    // 上传成功时的回调
    uploadSuccess(val, e, el) {
      if (e.response.code != 0) {
        this.$message.error(e.response.msg)
        return false
      }
      this.num++
      if (this.num == el.length) {
        this.num = el.length
        this.fileSuccess = true
      }
      clearTimeout(this.timer)
      this.timer = setTimeout(() => {
        this.$message.success('上传成功')
      }, 200)
      this.fileList = el
    },
    selectFocus(e, id) {
      // 根据材料id获取规格型号
      if (e) {
        if (id) {
          this.$https({
            url: '/material/listMaterialSpecsByMaterialId/?materialId=' + +id,
            method: 'post'
          })
            .then(res => {
              if (res.code === 0) {
                this.shipFrom.orderDeliveryDetailsList.forEach(element => {
                  if (id === element.materialId) {
                    this.$set(element, 'modelSelectList', res.data)
                  }
                })
              } else {
                this.$message.error(res.msg)
              }
            })
            .catch(err => {
              console.log(err)
            })
        } else {
          this.$message.error('请选择材料名称')
        }
      }
    },
    // 规格型号改变时设置单位
    categoryChange(val) {
      this.shipFrom.orderDeliveryDetailsList.forEach(element => {
        if (val === element.model) {
          element.modelSelectList.forEach(el => {
            if (el.specsName === val) {
              this.$set(element, 'company', el.materialUnit)
            }
          })
        }
      })
    },
    newMaterialClose(val) {
      if (val) {
        val.forEach(item => {
          this.shipFrom.orderDeliveryDetailsList.push({
            productTypes: 2,
            materialId: item.id,
            materialName: item.materialName,
            model: '',
            company: '',
            parameterIndex: '',
            unitPrice: 0,
            purchaseQuantity: 0,
            totalPrice: 0,
            modelSelectList: []
          })
        })
      }
      this.materialVisible = false
    },
    // 添加合同内材料弹窗关闭
    materialClose(val) {
      if (val) {
        this.shipFrom.orderDeliveryDetailsList = this.shipFrom.orderDeliveryDetailsList.concat(val)
        this.calculatePrice()
      }
      this.addMaterialVisiable = false
    },
    addMaterial(val) {
      if (val === '合同内') {
        if (this.orderFrom.contractId) {
          this.addMaterialVisiable = true
        } else {
          this.$message.error('请先选择合同编号')
        }
      } else {
        if (this.orderFrom.contractId) {
          this.materialVisible = true
        } else {
          this.$message.error('请先选择合同编号')
        }
      }
    },
    // 删除表格材料
    delTableItem(index) {
      this.shipFrom.orderDeliveryDetailsList.splice(index, 1)

      this.calculatePrice()
    },
    remove() {
      this.shipFrom.orderDeliveryDetailsList.forEach(item => {
        if (item.productTypes == 2) {
          this.$set(item, 'parameterIndex', '')
        }
        this.$set(item, 'unitPrice', '')
        this.$set(item, 'purchaseQuantity', '')
        this.$set(item, 'totalPrice', '')
      })
      this.calculatePrice()
    },
    // 计算总价
    calculatePrice() {
      let price = 0
      this.shipFrom.orderDeliveryDetailsList.forEach(item => {
        if (item.purchaseQuantity && item.unitPrice) {
          price = price + +(item.purchaseQuantity * item.unitPrice)
        }
      })
      this.shipFrom.realAmountPrice = price.toFixed(2)
    },
    // 计算价格
    contractPrice(e, index, prop) {
      if (e) {
        if (prop === 'purchaseQuantity') {
          if (!this.common.fieldTest('count', e)) {
            this.shipFrom.orderDeliveryDetailsList[index][prop] = 0
            this.$message.error('你输入的数量格式有误或超出范围,请重新输入')
            this.$set(this.shipFrom.orderDeliveryDetailsList[index], 'totalPrice', '')
            this.calculatePrice()
            return false
          }
        } else {
          if (!this.common.fieldTest('money', e)) {
            this.shipFrom.orderDeliveryDetailsList[index][prop] = 0
            this.$message.error('你输入的单价格式有误或超出范围,请重新输入')
            this.$set(this.shipFrom.orderDeliveryDetailsList[index], 'totalPrice', '')
            this.calculatePrice()
            return false
          }
        }
      }
      this.$set(this.shipFrom.orderDeliveryDetailsList[index], prop, e)
      if (
        this.shipFrom.orderDeliveryDetailsList[index].unitPrice &&
        this.shipFrom.orderDeliveryDetailsList[index].purchaseQuantity
      ) {
        let price =
          (this.shipFrom.orderDeliveryDetailsList[index].unitPrice *
            100 *
            this.shipFrom.orderDeliveryDetailsList[index].purchaseQuantity) /
          100
        this.$set(this.shipFrom.orderDeliveryDetailsList[index], 'totalPrice', price.toFixed(2))
      } else {
        this.$set(this.shipFrom.orderDeliveryDetailsList[index], 'totalPrice', '')
      }

      this.calculatePrice()
    },
    closeBtn() {
      this.$emit('close')
    },
    subBtn() {
      this.$set(this.shipFrom, 'contractOrderId', this.orderId)
      // 判断标书内清单是否存在未填写数量以及单价的
      let inBidFlag = this.shipFrom.orderDeliveryDetailsList.some(item => {
        return !item.purchaseQuantity || !item.unitPrice
      })

      if (!this.fileSuccess) {
        this.$message.error('请等待文件上传完毕')
        return false
      } else {
        if (this.fileList.length) {
          this.shipFrom.attachUrl = JSON.stringify(this.fileList)
        }
      }

      if (!this.common.fieldTest('phone', this.shipFrom.carrierPhone)) {
        this.$message.error('请输入正确的手机号')
        this.shipFrom.carrierPhone = ''
        return false
      } else if (!this.common.fieldTest('phone', this.shipFrom.supplierPhone)) {
        this.$message.error('请输入正确的手机号')
        this.shipFrom.supplierPhone = ''
        return false
      }

      if (inBidFlag) {
        this.$message.error('请填写货品清单的数量与单价,或删除不必要的材料')
        return false
      } else if (this.shipFrom.deliveryType == 1 && !this.shipFrom.licenseNumber) {
        this.$message.error('请输入车牌号')
        return false
      } else if (this.shipFrom.deliveryType == 2 && !this.shipFrom.trackingNumber) {
        this.$message.error('请输入物流单号')
        return false
      } else if (!this.shipFrom.deliveryDate) {
        this.$message.error('请选择发货日期')
        return false
      } else if (!this.shipFrom.carrier) {
        this.$message.error('请输入承运人')
        return false
      } else if (!this.shipFrom.carrierPhone) {
        this.$message.error('请输入承运人联系电话')
        return false
      } else if (!this.shipFrom.supplier) {
        this.$message.error('请输入供应方联系人')
        return false
      } else if (!this.shipFrom.supplierPhone) {
        this.$message.error('请输入供应方联系电话')
        return false
      } else if (!this.fileList.length) {
        this.$message.error('请上传发货附件')
        return false
      }
      this.$https({
        method: 'post',
        url: '/contractOrder/orderDelivery',
        data: this.shipFrom
      }).then(res => {
        if (res.code === 0) {
          this.$message.success(res.msg)
          this.$emit('saveShip')
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    tabRowClassName({ row, rowIndex }) {
      let index = rowIndex + 1
      if (index % 2 == 0) {
        return 'warning-row'
      }
    },
    getOrderData() {
      this.$https({
        method: 'post',
        url: '/contractOrder/orderDeliveryDetail?id=' + this.orderId
      })
        .then(res => {
          if (res.code === 0) {
            this.orderFrom = res.data
            this.shipFrom.orderDeliveryDetailsList = res.data.detailsList
            this.shipFrom.realAmountPrice = res.data.amountPrice
            this.shipFrom.acceptance = res.data.acceptance
            this.shipFrom.acceptancePhone = res.data.acceptancePhone
          } else {
            this.$message.error(res.msg)
          }
        })
        .catch(err => {
          console.log(err)
        })
    }
  }
}
</script>
<style lang="less" scoped>
.btn_box {
  display: flex;
  justify-content: space-between;
  margin: 20px 0;
}

#ship {
  /deep/.el-input.is-disabled .el-input__inner {
    border: 1px solid #d6d6d6 !important;
    background-color: #ebebeb !important;
  }
}
.btn_box {
  display: flex;
  margin: 20px 0;
}
.commonFrom {
  margin-top: 7px;
  width: 88%;
  .el-form-item {
    width: 45% !important;
    margin-bottom: 7px !important;
  }
  .form-item {
    width: 100% !important;
    /deep/.el-form-item__content {
      display: flex;
    }
    .el-input {
      width: 260px;
    }
  }

  .performance_text {
    color: #999;
    font-size: 14px;
  }
  .icon-guanbianniu {
    font-size: 16px;
    cursor: pointer;
    margin-left: 10px;
  }
  .icon-guanbianniu:hover {
    color: #fa7355;
  }
}
h1 {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  padding-left: 10px;
  border-left: 4px solid #fa7355;
  span {
    font-weight: normal;
    color: #999;
  }
}
.ty {
  color: #ff3d3d;
}
.footer {
  text-align: center;
  margin-top: 20px;
}
.mgn {
  margin-top: 20px;
}
.auditfrom {
  margin: 16px 0 0;
  .el-form-item {
    width: 43% !important;
    margin-bottom: 16px !important;
  }
}
.upload-wrap {
  /deep/.el-upload {
    display: none;
  }
  /deep/.el-upload-list {
    display: flex;
    align-items: center;
    width: 600px;
    flex-wrap: wrap;
    margin-bottom: 20px;
    .el-upload-list__item {
      width: 260px;
      margin: 20px 30px 0 0;
      background: #f0f1f2;
      border: 1px solid #d6d6d6;
    }
    .el-upload-list__item-name:hover {
      color: #fa7355;
    }
    .el-icon-close {
      &:hover {
        color: #fa7355;
      }
    }
  }
}
</style>
